package com.ruoyi.db.service.impl;

import java.util.List;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.isolar.comps.core.utils.DateUtils;
import com.isolar.comps.core.utils.lang.StringUtils;
import com.isolar.comps.core.web.domain.ResponseSgic;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.db.domain.SysDataSource;
import com.ruoyi.db.mapper.SysDataSourceMapper;
import com.ruoyi.db.service.ISysDataSourceService;

import cn.hutool.crypto.SecureUtil;

/**
 * @Description: 多数据源管理
 */
@Service
public class SysDataSourceServiceImpl extends ServiceImpl<SysDataSourceMapper, SysDataSource> implements ISysDataSourceService {

    //@Autowired
    //private DruidDataSourceCreator dataSourceCreator;
	@Autowired
    private SysDataSourceMapper sysDataSourceMapper;

    @Autowired
    private DataSource dataSource;

    @Override
    public ResponseSgic saveDataSource(SysDataSource sysDataSource) {
        try {
            long count = checkDbCode(sysDataSource.getCode());
            if (count > 0) {
                return ResponseSgic.fail("数据源编码已存在");
            }
            String dbPassword = sysDataSource.getDbPassword();
            if (StringUtils.isNotBlank(dbPassword)) {
                String encrypt = SecureUtil.aes().encryptHex(dbPassword);
                sysDataSource.setDbPassword(encrypt);
            }
            boolean result = save(sysDataSource);
            if (result) {
                //动态创建数据源
                //addDynamicDataSource(sysDataSource, dbPassword);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseSgic.success("添加成功！");
    }

    @Override
    public ResponseSgic editDataSource(SysDataSource sysDataSource) {
        try {
            SysDataSource d = getById(sysDataSource.getId());
            //DataSourceCachePool.removeCache(d.getCode());
            String dbPassword = sysDataSource.getDbPassword();
            if (StringUtils.isNotBlank(dbPassword)) {
                String encrypt = SecureUtil.aes().encryptHex(dbPassword);
                sysDataSource.setDbPassword(encrypt);
            }
            Boolean result=updateById(sysDataSource);
            if(result){
                //先删除老的数据源
               // removeDynamicDataSource(d.getCode());
                //添加新的数据源
                //addDynamicDataSource(sysDataSource,dbPassword);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseSgic.success("编辑成功!");
    }

    @Override
    public ResponseSgic deleteDataSource(String id) {
        SysDataSource sysDataSource = getById(id);
        //DataSourceCachePool.removeCache(sysDataSource.getCode());
        removeById(id);
        return ResponseSgic.success("删除成功!");
    }

    /**
     * 动态添加数据源 【注册mybatis动态数据源】
     *
     * @param sysDataSource 添加数据源数据对象
     * @param dbPassword    未加密的密码
     */
    private void addDynamicDataSource(SysDataSource sysDataSource, String dbPassword) {
//        DataSourceProperty dataSourceProperty = new DataSourceProperty();
//        dataSourceProperty.setUrl(sysDataSource.getDbUrl());
//        dataSourceProperty.setPassword(dbPassword);
//        dataSourceProperty.setDriverClassName(sysDataSource.getDbDriver());
//        dataSourceProperty.setUsername(sysDataSource.getDbUsername());
//        DynamicRoutingDataSource ds = (DynamicRoutingDataSource) dataSource;
//        DataSource dataSource = dataSourceCreator.createDataSource(dataSourceProperty);
//        try {
//            ds.addDataSource(sysDataSource.getCode(), dataSource);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }

    /**
     * 删除数据源
     * @param code
     */
    private void removeDynamicDataSource(String code) {
        //DynamicRoutingDataSource ds = (DynamicRoutingDataSource) dataSource;
        //ds.removeDataSource(code);
    }

    /**
     * 检查数据源编码是否存在
     *
     * @param dbCode
     * @return
     */
    private long checkDbCode(String dbCode) {
        QueryWrapper<SysDataSource> qw = new QueryWrapper();
        qw.lambda().eq(true, SysDataSource::getCode, dbCode);
        return count(qw);
    }
    
    /**
     * 查询数据源
     * 
     * @param id 数据源主键
     * @return 数据源
     */
    @Override
    public SysDataSource selectSysDataSourceById(String id)
    {
        return sysDataSourceMapper.selectSysDataSourceById(id);
    }

    /**
     * 查询数据源列表
     * 
     * @param sysDataSource 数据源
     * @return 数据源
     */
    @Override
    public List<SysDataSource> selectSysDataSourceList(SysDataSource sysDataSource)
    {
        return sysDataSourceMapper.selectSysDataSourceList(sysDataSource);
    }

    /**
     * 新增数据源
     * 
     * @param sysDataSource 数据源
     * @return 结果
     */
    @Override
    public int insertSysDataSource(SysDataSource sysDataSource)
    {
        sysDataSource.setCreateTime(DateUtils.getNowDate());
        return sysDataSourceMapper.insertSysDataSource(sysDataSource);
    }

    /**
     * 修改数据源
     * 
     * @param sysDataSource 数据源
     * @return 结果
     */
    @Override
    public int updateSysDataSource(SysDataSource sysDataSource)
    {
        sysDataSource.setUpdateTime(DateUtils.getNowDate());
        return sysDataSourceMapper.updateSysDataSource(sysDataSource);
    }

    /**
     * 批量删除数据源
     * 
     * @param ids 需要删除的数据源主键
     * @return 结果
     */
    @Override
    public int deleteSysDataSourceByIds(String ids)
    {
        return sysDataSourceMapper.deleteSysDataSourceByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除数据源信息
     * 
     * @param id 数据源主键
     * @return 结果
     */
    @Override
    public int deleteSysDataSourceById(String id)
    {
        return sysDataSourceMapper.deleteSysDataSourceById(id);
    }

}
